<?php
namespace App\Service\Member;

class UserService extends BaseService
{
    //用户

    /**
     * 注册
     * @param string $phone
     * @param string $pwd
     * @param string $yzm
     */
    public function regist($phone, $pwd, $yzm)
    {
        //看看手机号注册没有
        $uOne = (array) $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('off', 0)
            ->where('phone', $phone)
            ->first();
        if (!empty($uOne)) {
            return $this->toback(-2, '该手机号已注册');
        }
//        //看看验证码对不对
//        $yzmOne = (array) $this->dbConn($this->dbYzm)
//            ->where('phone', $phone)
//            ->where('code', $yzm)
//            ->first();
//        if (empty($yzmOne)) {
//            return $this->toback(-2, '验证码错误');
//        }
        $uname = toUname();
        $uData = [
            'phone' => $phone, 'uname' => $uname, 'passwd' => md5($pwd),
        ];
        $uData['uptime'] = $uData['addtime'] = toDate();
        $lastid = $this->dbConn($this->dbUser)->insertGetId($uData);
        if (!$lastid) {
            return $this->toback(-1, '注册失败');
        }
        //生成登录token
        //$token = md5($phone . time());
        $token = toToken();
        $logData = [
            'uid' => $lastid, 'uname' => $uname,
            'token' => $token, 'addtime' => toDate(),
        ];
        $this->dbConn($this->dbUlogin)->insertGetId($logData);
        $arys = [
            'token' => $token,
        ];
        return $this->toback(0 , '', $arys);
    }

    /**
     * 验证码保存
     * @param string $phone
     */
    public function yzmGet($phone)
    {
        $start = toDay().' 00:00:01';
        $end = toDay().' 23:59:59';
        $res = (array) $this->dbConn($this->dbYzm)
            ->where('phone', $phone)
            ->where('addtime', '>=', $start)
            ->where('addtime', '<=', $end)
            ->orderBy('id', 'desc')
            ->first();
        if (empty($res)) {
            $code = toRandStr();
            $lastid = $this->dbConn($this->dbYzm)->insertGetId([
                'phone' => $phone, 'code' => $code, 'addtime' => toDate(),
            ]);
            if (!$lastid) {
                return $this->toback(-1, '验证码失败');
            }
        } else {
            $code = $res['code'];
            $lastid = $res['id'];
        }
        $arys = [
            'code' => $code,
            'id' => $lastid,
        ];
        return $this->toback(0, '', $arys);
    }

    //短信更新
    public function yzmModify($id)
    {
        return $this->dbConn($this->dbYzm)->where('id', $id)
            ->update(['status' => 2, 'uptime' => toDate()]);
    }

    /**
     * 登录
     */
    public function dologin($phone, $pwd)
    {
        $uOne = (array) $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('off', 0)
            ->where('phone', $phone)
            ->first();
        if (empty($uOne)) {
            return $this->toback(-2, '没有该账号');
        }
        if ($uOne['passwd'] != md5($pwd)) {
            return $this->toback(-2, '密码错误');
        }
        //生成登录token
        //$token = md5($phone . time());
        $token = toToken();
        $logData = [
            'uid' => $uOne['id'], 'uname' => $uOne['uname'],
            'token' => $token, 'addtime' => toDate(),
        ];
        $this->dbConn($this->dbUlogin)->insertGetId($logData);
        $arys = [
            'token' => $token,
        ];
        return $this->toback(0 , '', $arys);
    }

    /**
     * 通过验证码登录
     * @param string $phone
     * @param string $yzm
     */
    public function loginByYzm($phone, $yzm)
    {
        $yzmOne = (array) $this->dbConn($this->dbYzm)
            ->where('phone', $phone)
            ->orderBy('id', 'desc')
            ->first();
        if (empty($yzmOne)) {
            return $this->toback(-2, '没有验证码');
        }
        if ($yzmOne['code'] != $yzm) {
            return $this->toback(-2, '验证码错误');
        }
        $res = (array) $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('off', 0)
            ->where('phone', $phone)
            ->orderBy('id', 'desc')
            ->first();
        if (empty($res)) {
            $uname = toUname();
            $token = toToken();
            $uData = [
                'phone' => $phone, 'uname' => $uname, 'passwd' => md5('123456'),
                'uptime' => toDate(), 'addtime' => toDate(),
            ];
            $lastid = $this->dbConn($this->dbUser)->insertGetId($uData);
            if (!$lastid) {
                return $this->toback(-1, '注册失败');
            }
            $log = $this->dbConn($this->dbUlogin)->insertGetId([
                'uid' => $lastid, 'uname' => $uname, 'token' => $token, 'addtime' => toDate(),
            ]);
            if (!$log) {
                return $this->toback(-1, '登录失败');
            }
        } else {
            $token = toToken();
            $log = $this->dbConn($this->dbUlogin)->insertGetId([
                'uid' => $res['id'], 'uname' => $res['uname'], 'token' => $token, 'addtime' => toDate(),
            ]);
            if (!$log) {
                return $this->toback(-1, '登录失败');
            }
        }
        return $this->toback(0, '', ['token' => $token]);
    }

    /**
     * 注销
     * @param string $token
     */
    public function logoff($token)
    {
        $logOne = (array) $this->dbConn($this->dbUlogin)
            ->where('token', $token)
            ->first();
        if (empty($logOne)) {
            return $this->toback(-2, '没有数据');
        }
        $uOne = (array) $this->dbConn($this->dbUser)
            ->where('off', 0)
            ->where('id', $logOne['uid'])
            ->first();
        if (empty($uOne)) {
            return $this->toback(-2, '没有账号');
        }
        $up = $this->dbConn($this->dbUser)->where('id', $uOne['id'])
            ->update(['off' => 1, 'offtime' => toDate()]);
        if (!$up) {
            return $this->toback(-1, '注销失败');
        }
        return $this->toback();
    }

    //实名认证申请
    public function authReal($uid, $pas)
    {
        $res = (array) $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('off', 0)
            ->where('id', $uid)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有用户');
        }
        $res = (array) $this->dbConn($this->dbUser)
            ->where('off', 0)
            ->where('realname', $pas['realname'])
            ->first();
        if (!empty($res)) {
            return $this->toback(-2, '存在同名数据');
        }
        $pas['uptime'] = toDate();
        $up = $this->dbConn($this->dbUser)->where('id', $uid)->update($pas);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    //获取用户信息
    public function infoByToken($token)
    {
        $log = (array) $this->dbConn($this->dbUlogin)
            ->where('token', $token)
            ->first();
        if (empty($log)) {
            return $this->toback(-2, '没有登录');
        }
        $res = (array) $this->dbConn($this->dbUser)
            ->where('id', $log['uid'])
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有用户');
        }
        $uhead = '';
        if ($res['head']) {
            if (file_exists($res['head'])) {
                $uhead = env('DOMAIN').'/'.$res['head'];
            } else if (substr($res['uid'], 0, 4) == 'http') {
                $uhead = $res['head'];
            }
        }
        $id_front = '';
        if ($res['id_front']) {
            if (file_exists($res['id_front'])) {
                $id_front = env('DOMAIN').'/'.$res['id_front'];
            } else if (substr($res['id_front'], 0, 4) == 'http') {
                $id_front = $res['id_front'];
            }
        }
        $id_back = '';
        if ($res['id_back']) {
            if (file_exists($res['id_back'])) {
                $id_back = env('DOMAIN').'/'.$res['id_back'];
            } else if (substr($res['id_back'], 0, 4) == 'http') {
                $id_back = $res['id_back'];
            }
        }
        $wx_account = '';
        if ($res['wx_account']) {
            if (file_exists($res['wx_account'])) {
                $wx_account = env('DOMAIN').'/'.$res['wx_account'];
            } else if (substr($res['wx_account'], 0, 4) == 'http') {
                $wx_account = $res['wx_account'];
            }
        }
        $utype_name = $res['utype']==1 ? '患者' : '医生';
        $arys = [
            'uid' => $res['id'],
            'uname' => $res['uname'],
            'realname' => $res['realname'],
            'phone' => $res['phone'],
            'type_name' => $utype_name,
            'sex_name' => $res['sex']==1 ? '男' : '女',
            'age' => $res['age'],
            'head' => $uhead,
            'address_now' => $res['address_now'],
            'id_card' => $res['id_card'],
            'id_front' => $id_front,
            'id_back' => $id_back,
            'wx_account' => $wx_account,
            'zfb_account' => $res['zfb_account'],
            'balance' => toNumber($res['balance']),
            'follow' => $res['follow'],
            'is_realname' => $res['is_realname'],
            'addtime' => $res['addtime'],
        ];
        return $this->toback(0, '', $arys);
    }

    //获取用户信息
    public function infoByUid($uid)
    {
        $res = (array) $this->dbConn($this->dbUser)
            ->where('id', $uid)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '没有用户');
        }
        $uhead = '';
        if ($res['head']) {
            if (file_exists($res['head'])) {
                $uhead = env('DOMAIN').'/'.$res['head'];
            } else if (substr($res['uid'], 0, 4) == 'http') {
                $uhead = $res['head'];
            }
        }
        $id_front = '';
        if ($res['id_front']) {
            if (file_exists($res['id_front'])) {
                $id_front = env('DOMAIN').'/'.$res['id_front'];
            } else if (substr($res['id_front'], 0, 4) == 'http') {
                $id_front = $res['id_front'];
            }
        }
        $id_back = '';
        if ($res['id_back']) {
            if (file_exists($res['id_back'])) {
                $id_back = env('DOMAIN').'/'.$res['id_back'];
            } else if (substr($res['id_back'], 0, 4) == 'http') {
                $id_back = $res['id_back'];
            }
        }
        $wx_account = '';
        if ($res['wx_account']) {
            if (file_exists($res['wx_account'])) {
                $wx_account = env('DOMAIN').'/'.$res['wx_account'];
            } else if (substr($res['wx_account'], 0, 4) == 'http') {
                $wx_account = $res['wx_account'];
            }
        }
        $utype_name = $res['utype']==1 ? '患者' : '医生';
        $arys = [
            'uid' => $res['id'],
            'uname' => $res['uname'],
            'realname' => $res['realname'],
            'phone' => $res['phone'],
            'type_name' => $utype_name,
            'sex_name' => $res['sex']==1 ? '男' : '女',
            'age' => $res['age'],
            'head' => $uhead,
            'address_now' => $res['address_now'],
            'id_card' => $res['id_card'],
            'id_front' => $id_front,
            'id_back' => $id_back,
            'wx_account' => $wx_account,
            'zfb_account' => $res['zfb_account'],
            'balance' => toNumber($res['balance']),
            'follow' => $res['follow'],
            'is_realname' => $res['is_realname'],
            'addtime' => $res['addtime'],
        ];
        return $this->toback(0, '', $arys);
    }

    /**
     * 设置关注
     * @param int $uid
     * @param int $blogUid
     */
    public function setFollow($uid, $blogUid)
    {
        $res = (array) $this->dbConn($this->dbUfollow)
            ->where('uid', $uid)
            ->where('uid_ed', $blogUid)
            ->first();
        if (!empty($res)) {
            return $this->toback(-2, '已关注');
        }
        $lastid = $this->dbConn($this->dbUfollow)->insertGetId([
            'uid' => $uid, 'uid_ed' => $blogUid, 'addtime' => toDate(),
        ]);
        if (!$lastid) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    //健康专栏
    public function healthyList($uid, $pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbTieba)
            ->where('del', 0)
            ->where('uid', $uid);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            //return $this->toback(-2, '没有记录');
            return $this->toback();
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $cateOne = (array) $this->dbConn($this->dbCate)
                ->where('id', $v['cate_id'])
                ->first();
            $cate_name = empty($cateOne) ? '-' : $cateOne['title'];
            $cnt = mb_strlen($v['cnt'])>50 ? mb_substr($v['cnt'], 0, 50).'...' : $v['cnt'];
            $arys[] = [
                'id' => $v['id'],
                'cate_name' => $cate_name,
                'title' => $v['title'],
                'cnt' => $cnt,
                'read_num' => $v['read_num'],
                'addtime' => $v['addtime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    //健康专栏详情
    public function healthyOne($id)
    {
        $res = (array) $this->dbConn($this->dbTieba)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            //return $this->toback(-2, '没有记录');
            return $this->toback();
        }
        $cateOne = (array) $this->dbConn($this->dbCate)
            ->where('id', $res['cate_id'])
            ->first();
        $cate_name = empty($cateOne) ? '-' : $cateOne['title'];
        $arys[] = [
            'id' => $res['id'],
            'cate_name' => $cate_name,
            'title' => $res['title'],
            'cnt' => $res['cnt'],
            'read_num' => $res['read_num'],
            'addtime' => $res['addtime'],
        ];
        return $this->toback(0, '', $arys);
    }

    /**
     * 保存微信信息
     * @param string $uid
     * @param string $openid
     * @return array
     */
    public function openidByToken($token, $openid)
    {
        if ($token) {
            $logOne = (array) $this->dbConn($this->dbUlogin)
                ->where('token', $token)
                ->orderBy('id', 'desc')
                ->first();
            if (empty($logOne)) {
                return $this->toback(-2, 'token错误');
            }
            $this->dbConn($this->dbUser)->where('id', $logOne['uid'])
                ->update(['openid' => $openid]);
        } else {
            $uOne = (array) $this->dbConn($this->dbUser)
                ->where('del', 0)
                ->where('off', 0)
                ->where('openid', $openid)
                ->first();
            if (empty($uOne)) {
                $uname = toUname();
                $lastid = $this->dbConn($this->dbUser)->insertGetId([
                    'uname' => $uname, 'passwd' => md5('123456'),
                    'openid' => $openid, 'addtime' => toDate(), 'uptime' => toDate(),
                ]);
                if (!$lastid) {
                    return $this->toback(-1, 'error');
                }
            } else {
                $lastid = $uOne['id'];
                $uname = $uOne['uname'];
            }
            $token = toToken();
            $this->dbConn($this->dbUlogin)->insertGetId([
                'uid' => $lastid, 'uname' => $uname, 'token' => $token, 'addtime' => toDate(),
            ]);
        }
        return $this->toback(0, '', $token);
    }

    /**
     * 提现列表
     * @param array $pages【start，limit】
     * @param int $uid
     */
    public function tixianList($pages, $uid)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbUtixian)
            ->where('status', 3)
            ->where('uid', $uid);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'desc')
            ->get();
        if (!count($res)) {
            return $this->toback();
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $arys[] = [
                'id' => $v['id'],
                'pay_way' => $v['pay_way'],
                'money' => toNumber($v['money']),
                'addtime' => $v['addtime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 提现申请
     * @param array $pas
     */
    public function tixianApply($pas)
    {
        $pas['addtime'] = toDate();
        $up = $this->dbConn($this->dbUtixian)->insertGetId($pas);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }
}